const path = require("path");
const fs = require("fs");
const router = require("koa-router")();



//创建一个方法进行筛选文件
function searchFiles() {
    let files = fs.readdirSync(__dirname);
    return files.filter((element) => {
        return element !== "index.js" && element.endsWith("js");
    })

}


//注册给定的路由数组下所有定义的路由
function registerfile(__dirname, files) {
    //遍历每个文件
    files.forEach((item) => {
        //为接受暴露的文件的绝对路径
        let tempfile = path.join(__dirname, item);
        //引用暴露的文件
        let routerobj = require(tempfile);
        console.log(routerobj);
        //遍历
        for (let r in routerobj) {
            console.log(r);
            let arrValue = routerobj[r];
            console.log(arrValue);

            //判断请求的方式
            let type = routerobj[r][0];
            if (type === "get") {
                // 为了判断传入的数组里面有没有包含auth，没有正按正常处理；有的话，需要auth传入作为第二参数
                if (arrValue.length === 2) {
                    let fn = arrValue[1];
                    router.get(r, fn);
                } else {
                    let auth = arrValue[1];
                    let fn = arrValue[2];
                    router.get(r, auth, fn);
                }

            } else {
                if (arrValue.length === 2) {
                    let fn = arrValue[1];
                    router.post(r, fn);
                } else {
                    let auth = arrValue[1];
                    let fn = arrValue[2];
                    router.post(r, auth, fn);
                }
            }
        }

    })
}


module.exports = function () {
    let files = searchFiles();
    registerfile(__dirname, files);
    //引用中间件router
    return router.routes();

}











